const fs = require("fs");
const { root } = require("../../config.json");
const { getDefaultBlock, themeList } = require("../tool/util");
const { writeFile, fsExistsSync } = require("../../app/util");

function tempConfigTobLibConfig(temp) {
    const defaultDirPath = `./src/theme/${temp}/config/settings_schema.json`;
    const dataPath = `./src/theme/${temp}/config/settings_data.json`;
    const settings_schema = JSON.parse(fs.readFileSync(defaultDirPath, "utf-8"));
    const settings_data = JSON.parse(fs.readFileSync(dataPath, "utf-8"));
    const block = { default_blocks_setting: { mode: "", exclude_block_ids: [] }, list: [] };
    block.list = settings_schema.blocks_setting.map((item) => {
        item.sections = item.sections.map((item) => item.id);
        return item;
    });
    if (settings_schema.default_blocks_setting) {
        block.default_blocks_setting = settings_schema.default_blocks_setting;
    }

    const page = settings_schema.pages_setting.map((item) => {
        const pageSetting = settings_data.pages_settings.find((setting) => setting.route === item.route);
        return {
            name: item.name,
            route: item.route,
            max_block: item.max_block,
            route_handle: item.route_handle,
            layout: true,
            sections: item.sections
                .map((el, index) => {
                    let sections;
                    if (pageSetting && !["header", "footer"].includes(el.type)) {
                        const section = pageSetting.sections.filter((section) => section.type === el.type);
                        if (section.length) {
                            if (section.length > 1) {
                                sections = pageSetting.sections[index === 0 ? index : index - 1].params;
                            } else {
                                sections = section[0].params;
                            }
                        }
                    }

                    return {
                        type: el.type,
                        fixed: el.fixed,
                        params: sections
                    };
                })
                .filter((el) => !["header", "footer"].includes(el.type))
        };
    });

    const global = settings_schema.global_setting.map((item) => {
        item.settings = item.settings.map((el) => {
            el["default"] = settings_data.global[el.id];
            return el;
        });
        return item;
    });
    writeFile(`./src/theme/${temp}/lib/config/block.json`, JSON.stringify(block, "", "\t"));
    writeFile(`./src/theme/${temp}/lib/config/page.json`, JSON.stringify(page, "", "\t"));
    writeFile(`./src/theme/${temp}/lib/config/global.json`, JSON.stringify(global, "", "\t"));
}

function setRouterSections(sections, blocksSetting) {
    return sections.map((section) => {
        return {
            type: section.type,
            fixed: section.fixed === "top" ? 1 : section.fixed === "bottom" ? 3 : 2,
            params: section.params || (blocksSetting[section.type] ? blocksSetting[section.type].default : "")
        };
    });
}

function libConfigToTempConfig(temp) {
    const blocksSetting = getDefaultBlock(`./src/theme/${temp}/sections`);
    let settingsData = { global: { sections: {} }, pages_settings: [] };
    let settingsScheme = { global_setting: [], pages_setting: [], blocks_setting: [], default_blocks_setting: {} };
    const global = JSON.parse(fs.readFileSync(`./src/theme/${temp}/lib/config/global.json`, "utf-8"));
    settingsScheme.global_setting = global;
    global.forEach((element) => {
        element.settings.forEach((setting) => {
            settingsData.global[setting.id] = setting.default;
        });
    });
    settingsData.global.sections["header"] = blocksSetting["header"].default;
    settingsData.global.sections["footer"] = blocksSetting["footer"].default;

    const blockContent = JSON.parse(fs.readFileSync(`./src/theme/${temp}/lib/config/block.json`, "utf-8"));
    settingsScheme.default_blocks_setting = blockContent.default_blocks_setting;
    settingsScheme.blocks_setting = blockContent.list.map((blocks) => {
        blocks.sections = blocks.sections.map((block) => {
            if (blocksSetting[block]) {
                return {
                    name: blocksSetting[block].name,
                    type: "block",
                    icon: blocksSetting[block].icon,
                    routes: blocksSetting[block].routes || [],
                    id: block
                };
            }
            return {
                type: "block",
                id: block
            };
        });
        return blocks;
    });

    //生成页面配置
    const pageContent = JSON.parse(fs.readFileSync(`./src/theme/${temp}/lib/config/page.json`, "utf-8"));
    pageContent.forEach((element, index) => {
        settingsData.pages_settings.push({
            route: element.route,
            route_handle: element.route_handle,
            sections: setRouterSections(element.sections, blocksSetting)
        });

        settingsScheme.pages_setting.push({
            name: element.name,
            route: element.route,
            max_block: element.max_block,
            route_handle: element.route_handle,
            sections: []
        });

        element.sections.forEach((setting) => {
            settingsScheme.pages_setting[index].sections.push({
                type: setting.type,
                fixed: setting.fixed,
                name: blocksSetting[setting.type] ? blocksSetting[setting.type].name : {}
            });
        });
        if (element.layout) {
            settingsScheme.pages_setting[index].sections.unshift({
                type: "header",
                fixed: "top",
                name: {
                    zh_CN: "页头",
                    en_US: "Page header"
                }
            });
            settingsScheme.pages_setting[index].sections.push({
                type: "footer",
                fixed: "bottom",
                name: {
                    zh_CN: "页尾",
                    en_US: "Page footer"
                }
            });
        }
    });
    writeFile(`./src/theme/${temp}/config/settings_data.json`, JSON.stringify(settingsData, "", "\t"));
    writeFile(`./src/theme/${temp}/config/settings_schema.json`, JSON.stringify(settingsScheme, "", "\t"));
}
// tempConfigTobLibConfig("puaintapets");

function buildAllConfig() {
    const list = themeList();
    list.forEach((item) => {
        if (fsExistsSync(`./src/theme/${item}/config`)) {
            libConfigToTempConfig(item);
        }
    });
}

tempConfigTobLibConfig("default");

// buildAllConfig();
